package cn.zxh.csdn_maven.atomy.auth.letter;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.HttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.zxh.csdn_maven.atomy.auth.GetSourceList.AbstractSource;
import cn.zxh.csdn_maven.base.util.GetHtmlFromUrl;

/**
 * 获取关系圈
 * 
 * @author zxh
 * 
 */
public class RelationSource extends AbstractSource {
	private Integer pageSize = 50;
	private String type = "fans";

	public RelationSource setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
		return this;
	}

	public RelationSource setType(String type) {
		this.type = type;
		return this;
	}

	@Override
	public Map<String, Object> execute(HttpClient client, Map<String, Object> params) throws Exception {
		Map<String, Object> resulMap = new HashMap<String, Object>();
		String baseUrl = getBaseUrl();
		if (params == null) {
			params = new HashMap<String, Object>();
		}
		if (params != null && params.get("times") != null) {
			baseUrl = String.format(baseUrl, Integer.valueOf(params.get("times").toString()), pageSize, type);
		} else {
			/** csdn限制最大限额获取50个 */
			baseUrl = String.format(baseUrl, 1, pageSize, type);
		}
		params.put("base_url", baseUrl);
		String html = GetHtmlFromUrl.getInstance().getHtml(params);
		JSONObject jsonObject = new JSONObject(html);
		/** 计算总页数 */
		if (params.get("times") == null) {
			double total = jsonObject.getJSONObject("result").getDouble("fans_num");
			int times = (int) Math.ceil(total / pageSize);
			resulMap.put("times", times);
		}
		/** 获取用户列表 */
		JSONArray userList = jsonObject.getJSONObject("result").getJSONArray("list");
		resulMap.put("userSource", userList);
		return resulMap;
	}

	@Override
	public String getBaseUrl() {
		return "http://my.csdn.net/service/main/my_relation?pageno=%1$d&pagesize=%2$d&type=%3$s";
	}

}
